﻿using AutoMapper;
using BackData;
using Domain.Quality;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Equipment;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Hanldler.Equipment
{
    /// <summary>
    /// 创建设备命令的处理器
    /// <para>实现了MediatR的IRequestHandler接口，负责处理CreateEquipmentCommand命令，完成设备创建的业务逻辑</para>
    /// </summary>
    public class CreateEquipmentHandler : IRequestHandler<CreateEquipmentCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IRepository<Equipmentmodel> equiRep;
        private readonly ILogger<CreateEquipmentHandler> logger;

        /// <summary>
        /// 构造函数，注入依赖服务
        /// </summary>
        /// <param name="mapper">AutoMapper 实例，用于对象映射</param>
        /// <param name="equiRep">设备仓储接口，封装数据访问逻辑</param>
        /// <param name="db">SqlSugar 数据库客户端，用于直接执行数据库操作</param>
        public CreateEquipmentHandler(IMapper mapper,IRepository<Equipmentmodel> equiRep,ILogger<CreateEquipmentHandler> logger)
        {
            this.mapper = mapper;
            this.equiRep = equiRep;
            this.logger = logger;
        }
        public async Task<APIResult<int>> Handle(CreateEquipmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"此操作在{DateTime.Now}成功执行了");
                var result = mapper.Map<Equipmentmodel>(request);
                result.Id = YitIdHelper.NextId();
                var r = await equiRep.AddAsync(result);
                if (r > 0)
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.OK,
                        Message = "设备添加成功",
                        Result = r
                    };
                }
                else
                {
                    return new APIResult<int>
                    {
                        Code = StateCode.Fail,
                        Message = "设备添加失败",
                        Result = r
                    };
                }
            }
            catch (Exception ex)
            {
                logger.LogError("设备添加失败了" + ex.Message);
                throw;
            }
        }
    }
}
